package com.school.campus.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import com.school.common.constant.ActivityCacheConstants;
import com.school.campus.service.IActivityService;
import com.school.campus.service.redis.ActivityRedisService;

/**
 * Redis键过期监听器
 */
@Component
public class RedisKeyExpirationListener implements MessageListener {

    @Autowired
    private IActivityService activityService;

    @Autowired
    private ActivityRedisService activityRedisService;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取过期的键
        String expiredKey = message.toString();

        // 处理活动开始提醒
        if (expiredKey.startsWith(ActivityCacheConstants.ACTIVITY_START_REMIND_KEY)) {
            String activityId = expiredKey.substring(ActivityCacheConstants.ACTIVITY_START_REMIND_KEY.length());
            // 更新活动状态为进行中
            activityService.dealWithActivity(activityId, 2L);
            // 刷新缓存
            activityRedisService.cacheActivity(activityService.selectActivityById(activityId));
        }

        // 处理活动结束提醒
        if (expiredKey.startsWith(ActivityCacheConstants.ACTIVITY_END_REMIND_KEY)) {
            String activityId = expiredKey.substring(ActivityCacheConstants.ACTIVITY_END_REMIND_KEY.length());
            // 更新活动状态为已结束
            activityService.dealWithActivity(activityId, 3L);
            // 刷新缓存
            activityRedisService.cacheActivity(activityService.selectActivityById(activityId));
        }
    }
}